package com.dragonfly.shutter.services;

import java.util.Date;
import java.util.List;

import com.dragonfly.shutter.DAOs.BrowseLogDAO;
import com.dragonfly.shutter.DAOs.PictureDAO;
import com.dragonfly.shutter.DAOs.TagDAO;
import com.dragonfly.shutter.beans.BrowseLog;
import com.dragonfly.shutter.beans.PictureDetail;
import com.dragonfly.shutter.beans.Tag;
import com.dragonfly.shutter.utils.ListOperation;

public class PictureEditService {
	private PictureDAO pictureDAO;
	private BrowseLogDAO browseLogDAO;
	private TagDAO tagDAO;

	/**
	 * 服务类，处理编辑图片属性的请求
	 * @param picture 图片Bean
	 * @param tagString 标签String
	 * @param requestUrl 请求的页面URL
	 */
	@SuppressWarnings("unchecked")
	public void doService(PictureDetail picture, List<String> tags, String requestUrl){
		//标签处理
		List<String> tagDelete = ListOperation.minus(picture.getPictureTags(), tags);  //需要被删除的标签
		List<String> tagNew = ListOperation.minus(tags, picture.getPictureTags());	//需要新加入的标签
		
		doDBOperate(picture, requestUrl, tagDelete, tagNew);
	}
	
	/**
	 * 相册编辑数据库操作
	 * @param picture
	 * @param requestUrl
	 * @param tagDelete
	 * @param tagNew
	 */
	public void doDBOperate(PictureDetail picture, String requestUrl,
			List<String> tagDelete, List<String> tagNew){		
		BrowseLog browseLog = new BrowseLog();
		browseLog.setUserID(picture.getPicOwner().getUserID());
		browseLog.setBrowseTime(new Date(System.currentTimeMillis()));
		browseLog.setUrl(requestUrl);
		
		pictureDAO.updatePictureByID(picture);
		browseLogDAO.insertBrowseLog(browseLog);
		
		for(String str : tagDelete){
			tagDAO.deletePictureTag(picture.getPictureID(), tagDAO.selectTagByName(str).getTagID());
		}
		
		for(String str : tagNew){
			Tag tag = tagDAO.selectTagByName(str);
			
			if( tag == null ){
				tag = new Tag();
				
				if(str != null && !str.trim().equals("")){
					tag.setTagName(str);
					tagDAO.insertTag(tag);
					tag = tagDAO.selectTagByName(str);
					System.out.println(tag.getTagID());
					tagDAO.insertPictureTag(picture.getPictureID(), tag.getTagID());
				}
			}
		}
		
		picture.setPictureTags(tagDAO.selectTagByPictureID(picture.getPictureID()));
	}
	

	public void setPictureDAO(PictureDAO pictureDAO) {
		this.pictureDAO = pictureDAO;
	}

	public void setBrowseLogDAO(BrowseLogDAO browseLogDAO) {
		this.browseLogDAO = browseLogDAO;
	}

	public void setTagDAO(TagDAO tagDAO) {
		this.tagDAO = tagDAO;
	}

	public PictureDAO getPictureDAO() {
		// TODO Auto-generated method stub
		return this.pictureDAO;
	}
}
